<script setup lang="ts">
import { debounce } from 'lodash-es'
import elementResizeDetectorMaker from 'element-resize-detector'
import WarningStatisticChart from './WarningStatisticChart.vue'
import upImg from './up.png'
import downImg from './down.png'
import { getWarningStatistics } from '@/api/modules/alarm'

const erd = elementResizeDetectorMaker()
const container = ref<HTMLElement | null>(null)
const type = ref<0 | 1 | 2>(0)
const statisticsData = shallowRef<any>({})
const dataset = computed(() => {
  const s = unref(statisticsData)
  const names = (s.dataList || []).map((item: any) => item.title)
  const values = (s.dataList || []).map((item: any) => item.value)
  return [
    ['日期', ...names],
    ['告警次数', ...values],
  ]
})

const total = computed(() => {
  const s = unref(statisticsData)
  return s.totalNum
})
const huanbi = computed(() => {
  const s = unref(statisticsData)
  return Number(s.monNum)
})

const chart = ref<InstanceType<typeof WarningStatisticChart>>()
const listener = debounce((el: HTMLElement) => {
  const w = el.clientWidth
  const h = el.clientHeight
  chart.value?.resize(w, h)
}, 300)

async function getData() {
  try {
    const { data } = await getWarningStatistics(unref(type))
    statisticsData.value = data
  }
  catch (e) {}
}

watchEffect(() => {
  getData()
})

onMounted(() => {
  if (container.value) {
    erd.listenTo(container.value, listener)
  }
})
</script>

<template>
  <div class="alpha-block flex flex-col">
    <div class="flex items-center p-3">
      <span class="pl-2 line-height-none" style="border-left: 4px solid var(--el-color-primary);">告警统计</span>
      <div class="ml-auto flex items-center">
        <ElRadioGroup v-model="type" style="--el-border: 1px solid #888;" size="small">
          <ElRadioButton label="本周" :value="0" />
          <ElRadioButton label="本月" :value="1" />
          <ElRadioButton label="本年" :value="2" />
        </ElRadioGroup>
      </div>
    </div>
    <div class="fs-14 flex items-center p-3">
      <span>报警数量：</span>
      <span>{{ total }}</span>
      <span class="ml-10">环比：</span>
      <span :style="huanbi > 0 ? 'color: #ff3131;' : 'color: #2bd070;'">{{ huanbi }}%</span>
      <img class="ml-2" :src="huanbi > 0 ? upImg : downImg">
    </div>
    <div ref="container" class="flex-auto overflow-auto">
      <WarningStatisticChart ref="chart" name="" :data="dataset" />
    </div>
  </div>
</template>
